package com.holyn.guofang.view.Login;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.holyn.guofang.MyApplication;
import com.holyn.guofang.R;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.view.distinguish.AlgorithmActivity;
import com.holyn.guofang.view.distinguish.AlgorithmSelectActivity;
import com.holyn.guofang.view.distinguish.ImageElementActivity;
import com.holyn.guofang.viewcommon.dialog.UpdateAppDialog;
import com.holyn.guofang.model.sharepreference.AppSharePreference;
import com.holyn.guofang.model.sharepreference.UserInfoSharePreference;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.UpdateInfoWo;
import com.holyn.guofang.model.webhttp.wo.UserInfoWo;
import com.holyn.guofang.presenter.login.LoginContract;
import com.holyn.guofang.presenter.login.LoginPresenter;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.view.home.HomeActivity;
import com.holyn.guofang.viewcommon.dialog.UpdateAppDialog2;
import com.vondear.rxtools.RxAppUtils;
import com.vondear.rxtools.view.dialog.RxDialogSure;

import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import zlc.season.rxdownload2.entity.DownloadStatus;

public class LoginActivity extends BaseActivity implements BaseView, LoginContract.View {

    private static final int REQUEST_ACTION_UPDATE_CHECK = 0x0001;
    private static final int REQUEST_ACTION_UPDATE_DOWNLOAD = 0x0002;
    private static final int REQUEST_ACTION_LOGIN = 0x0003;

    public static final int REQUEST_CODE_REGISTER = 0x0001;

    @BindView(R.id.et_valid_code)
    EditText etValidCode;
    @BindView(R.id.btn_login_submit)
    Button btnLoginSubmit;
    @BindView(R.id.sv_login_form)
    ScrollView svLoginForm;
    @BindView(R.id.et_user_name)
    EditText etUserName;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_change_language)
    TextView tvChangeLanguage;
//    @BindView(R.id.tv_get_password)
//    TextView tvGetPassword;
    @BindView(R.id.iv_clear_name)
    ImageView ivClearName;
    @BindView(R.id.iv_clear_password)
    ImageView ivClearPassword;
//    @BindView(R.id.tv_com_name)
//    TextView tvComName;
//    @BindView(R.id.cb_remember_password)
//    CheckBox cbRememberPassword;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.ll_valid_code)
    LinearLayout llValidCode;

    private LoginContract.Presenter loginPresenter;
    private UpdateAppDialog2 updateAppDialog;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_login;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);

        loginPresenter = new LoginPresenter(LoginActivity.this);
        loginPresenter.addViewListener(this);
        loginPresenter.postPlatformUpdate(REQUEST_ACTION_UPDATE_CHECK);
        initView();
        initUpdateAppDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loginPresenter.resume();
        initAppLanguage();
    }

    private void initView() {
//        etPassword.setText(UserInfoSharePreference.getPassword(LoginActivity.this));
        etUserName.setText(UserInfoSharePreference.getMobile(LoginActivity.this));
//        cbRememberPassword.setChecked(AppSharePreference.getIsRememberPassword(LoginActivity.this));

        tvVersion.setText("V"+RxAppUtils.getAppVersionName(LoginActivity.this));

        etUserName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                LogUtils.d("hasFocus:" + hasFocus);
            }
        });
        etUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    ivClearName.setVisibility(View.GONE);
                } else {
                    ivClearName.setVisibility(View.VISIBLE);
                }
            }
        });

        etValidCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    ivClearPassword.setVisibility(View.GONE);
                } else {
                    ivClearPassword.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void initUpdateAppDialog() {
        updateAppDialog = new UpdateAppDialog2(LoginActivity.this);
//        updateAppDialog = new UpdateAppDialog2(LoginActivity.this, null, (dialogInterface, i) -> {
//            LoginActivity.this.finish();
//        });
    }

//    @OnClick(R.id.btn_login_submit)
//    public void onViewClicked() {

//        attemptLogin();

    //测试上传
//        File file1 = new File(Environment.getExternalStorageDirectory()+"/0221.jpg");
//        File file2 = new File(Environment.getExternalStorageDirectory()+"/0222.jpg");
//        List<File> files = new ArrayList<>();
//        files.add(file1);
//        files.add(file2);
//        loginPresenter.postUploadTest(files);

    //测试下载

//        loginPresenter.postDownloadTest();

//    }

    @OnClick({R.id.btn_login_submit, R.id.tv_change_language, R.id.tv_register, R.id.tv_get_password, R.id.iv_clear_name, R.id.iv_clear_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login_submit:
//                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
//                LoginActivity.this.finish();
                attemptLogin();
                break;
            case R.id.tv_register:
                RegisterActivity.startForResult(LoginActivity.this, REQUEST_CODE_REGISTER);
                break;
            case R.id.tv_change_language:
                changeAppLanguage();
                break;
            case R.id.tv_get_password:
                startActivity(new Intent(LoginActivity.this, GetPasswordActivity.class));
                break;
            case R.id.iv_clear_name:
                etUserName.setText("");
                break;
            case R.id.iv_clear_password:
                etValidCode.setText("");
                break;
        }
    }

    private void attemptLogin() {
        etUserName.setError(null);
        etValidCode.setError(null);

        boolean isShowLLlValidCode = llValidCode.isShown();

        String userName = etUserName.getText().toString().trim();
//        String password = etPassword.getText().toString().trim();
        String validCode = etValidCode.getText().toString().trim();

        if (TextUtils.isEmpty(userName)) {
            etUserName.setError("请输入手机号码");
            etUserName.requestFocus();
            return;
        } else if (!isUserNameValid(userName)) {
            etUserName.setError("手机号码不符合规则");
            etUserName.requestFocus();
            return;
        }

        if (isShowLLlValidCode) {
            if (TextUtils.isEmpty(validCode)) {
                etValidCode.setError("请输入验证码");
                etValidCode.requestFocus();
                return;
            }
        }
        showLoadingDialog();
//        loginPresenter = new LoginPresenter(LoginActivity.this);//cao, retrofit没重新实例化，device没重新获取，刚安装时在ocreate里的retrofit获得的divide不一样，坑，原因是刚安装没有足够权限
        loginPresenter.postLoginB(userName, validCode, REQUEST_ACTION_LOGIN);
    }

    private boolean isUserNameValid(String email) {
        //TODO: Replace this with your own logic
//        return email.contains("@");
        return true;
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
//        return password.length() > 4;
        return true;
    }

    @Override
    public void requestStart(Integer requestAction) {
        switch (requestAction) {
            case REQUEST_ACTION_UPDATE_DOWNLOAD:

                break;
        }
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        closeLoadingDialog();
        toastMsg("登录出现异常");
        switch (requestAction) {
            case REQUEST_ACTION_UPDATE_DOWNLOAD:
                updateAppDialog.dismiss();
                break;
        }
    }

    @Override
    public void requestComplete(Integer requestAction) {
        closeLoadingDialog();

        switch (requestAction) {
            case REQUEST_ACTION_UPDATE_DOWNLOAD:
                updateAppDialog.dismiss();
                break;
        }
    }

    @Override
    public void responseSuccess(Integer requestAction, UserInfoWo userInfoWo) {
//        LogUtils.d(userInfoWo);
        LogUtils.json(userInfoWo.toString());//更改为json格式输出
        switch (requestAction) {
            case REQUEST_ACTION_LOGIN:
                if (userInfoWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                    toastMsg("登录成功");
                    UserInfoSharePreference.saveUserInfo(LoginActivity.this, userInfoWo);

//                    AppSharePreference.saveIsRememberPassword(LoginActivity.this, cbRememberPassword.isChecked());
//                    if (cbRememberPassword.isChecked()){
//                        UserInfoSharePreference.savePassword(LoginActivity.this, etPassword.getText().toString().trim());
//                    } else {
//                        UserInfoSharePreference.savePassword(LoginActivity.this, "");
//                    }

                    if (llValidCode.isShown()) {
                        llValidCode.setVisibility(View.GONE);
                    }

                    startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                    LoginActivity.this.finish();

                } else if (userInfoWo.getStatus() == -2){
                    toastMsg("设备有变，需要验证");
                    llValidCode.setVisibility(View.VISIBLE);
                } else {
//                    toastMsg(HttpConfigure.getLoginStatusMsg(userInfoWo.getStatus(), userInfoWo.getErr()));
//                    showLoadingDialog();
                    toastMsg("登录失败");
 /******************************注释学习错误❌弹窗信息！**********************************************/
                    //提示弹窗
                    final RxDialogSure rxDialogSure = new RxDialogSure(this);
                    rxDialogSure.getIvLogo().setVisibility(View.GONE);
                    rxDialogSure.setTitle("❌错误❌");
                    rxDialogSure.setContent("status："+userInfoWo.getStatus()+"\n"+userInfoWo.getErr());
                    rxDialogSure.getTvSure().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            rxDialogSure.cancel();
                        }
                    });
                    rxDialogSure.show();
/******************************注释学习错误❌弹窗信息！**********************************************/
                }
                break;
        }
    }

    @Override
    public void responseSuccessGetUpdateInfoWo(Integer requestAction, UpdateInfoWo updateInfoWo) {
        if (updateInfoWo.getNeedUpdate()) {
            updateAppDialog.setTvVersion(updateInfoWo.getUpdateInfo().getVersion()+"");
            updateAppDialog.setTvContent(updateInfoWo.getUpdateInfo().getUpdateInformation());
            updateAppDialog.setDownUrl(updateInfoWo.getUpdateInfo().getURL());
            updateAppDialog.show();
        }
    }

    @Override
    public void responseDownloadNewAppStatus(Integer requestAction, DownloadStatus downloadStatus) {

    }

    @Override
    public void responseDownloadNewAppComplete(Integer requestAction, Uri uri) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK){
            switch (requestCode){
                case REQUEST_CODE_REGISTER:
                    String userName = data.getStringExtra(RegisterActivity.INTENT_KEY_USER_NAME);
                    String password = data.getStringExtra(RegisterActivity.INTENT_KEY_PASSWORD);
                    etUserName.setText(userName);
//                    etPassword.setText(password);
                    break;
            }
        }
    }

    private void initAppLanguage() {
        String language = AppSharePreference.getAppLanguage(MyApplication.getContext());
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration conf = resources.getConfiguration();
        LogUtils.d("初始化前：" + conf.locale);
        if (language.equals(AppSharePreference.L_CHINESE)) {
            conf.locale = Locale.CHINESE;
        } else if (language.equals(AppSharePreference.L_ENGLISH)) {
            conf.locale = Locale.ENGLISH;
        }
        resources.updateConfiguration(conf, dm);
        LogUtils.d("初始化后：" + conf.locale);
    }

    public void changeAppLanguage() {
        String language = AppSharePreference.getAppLanguage(MyApplication.getContext());
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration conf = resources.getConfiguration();

        if (language.equals(AppSharePreference.L_CHINESE)) {
            language = AppSharePreference.L_ENGLISH;
            conf.locale = Locale.ENGLISH;
        } else if (language.equals(AppSharePreference.L_ENGLISH)) {
            language = AppSharePreference.L_CHINESE;
            conf.locale = Locale.CHINESE;
        }
        resources.updateConfiguration(conf, dm);
        AppSharePreference.setAppLanguage(MyApplication.getContext(), language);

        changeCurPageLanguage(language);
    }

    private void installApk(Uri uri) {
        RxAppUtils.installApp(LoginActivity.this, uri.getPath());
    }

    public void changeCurPageLanguage(String language) {
        if (language.equals(AppSharePreference.L_CHINESE)) {
            btnLoginSubmit.setText("登录");
            tvRegister.setText("用户注册");
            tvChangeLanguage.setText("切换语言");
//            tvGetPassword.setText("忘记密码");
//            cbRememberPassword.setText("记住密码");
        } else if (language.equals(AppSharePreference.L_ENGLISH)) {
            btnLoginSubmit.setText("Login");
            tvRegister.setText("Register");
            tvChangeLanguage.setText("Switch Language");
//            tvGetPassword.setText("Forget Password");
//            cbRememberPassword.setText("Remember Password");
        }
    }
}

